@file:Suppress("UNCHECKED_CAST")

package moe.fuqiuluo.api


import com.tencent.mobileqq.channel.SsoPacket
import com.tencent.mobileqq.sign.QQSecuritySign
import kotlinx.serialization.Serializable
import moe.fuqiuluo.CONFIG
import moe.fuqiuluo.ext.*

@Serializable
data class Sign(
    val token: String,
    val extra: String,
    val sign: String,
    val o3did: String,
    val requestCallback: List<SsoPacket>
)

fun sign(
    uin: Long,
    cmd: String,
    seq: Int,
    buffer: ByteArray
): Sign {
    val session = findSession(uin)
    val vm = session.vm

    val list = arrayListOf<SsoPacket>()
    lateinit var o3did: String

    val sign = session.withLock {
        QQSecuritySign.getSign(vm, CONFIG.protocol.qua, cmd, buffer, seq, uin.toString()).value.also {
            o3did = vm.global["o3did"] as? String ?: ""
            val requiredPacket = vm.global["PACKET"] as ArrayList<SsoPacket>
            list.addAll(requiredPacket)
            requiredPacket.clear()
        }
    }

    return Sign(
        sign.token.toHexString(),
        sign.extra.toHexString(),
        sign.sign.toHexString(), o3did, list
    )
}